package cn.wellwhz.listener;

import cn.nukkit.Player;
import cn.nukkit.block.BlockID;
import cn.nukkit.event.EventHandler;
import cn.nukkit.event.Listener;
import cn.nukkit.event.player.PlayerToggleSneakEvent;
import cn.nukkit.level.Position;
import cn.wellwhz.WIronElevator;
import cn.wellwhz.event.PlayerIronElevatorEvent;

import java.util.HashMap;

public class PlayerDownstairsListener implements Listener {
    public final int minHeight = WIronElevator.ins.getConfig().getInt("电梯最近距离");
    public final int maxHeight = WIronElevator.ins.getConfig().getInt("电梯最远距离");
    public HashMap<String, Long> playerUseTime = new HashMap<>();

    @EventHandler
    public void onPlayerToggleSneak(PlayerToggleSneakEvent ent) {
        Player p = ent.getPlayer();

        //防止反复触发
        if (playerUseTime.get(p.getName()) != null && System.currentTimeMillis() - playerUseTime.get(p.getName()) < 150)
            return;
        playerUseTime.put(p.getName(), System.currentTimeMillis());

        if (p.hasPermission("wironelevator.use") &&
                (p.getPosition().add(0, -1, 0).getLevelBlock().getId() == BlockID.IRON_BLOCK ||
                        p.getPosition().add(0, -2, 0).getLevelBlock().getId() == BlockID.IRON_BLOCK)) {
            Position pos = p.getPosition();
            for (int i = minHeight; i<= maxHeight; i++) {
                if (pos.add(0, -i, 0).getLevelBlock().getId() == BlockID.IRON_BLOCK) {
                    if (pos.add(0, -i + 1, 0).getLevelBlock().getId() == BlockID.AIR &&
                            pos.add(0, -i + 2, 0).getLevelBlock().getId() == BlockID.AIR) {
                        //防止卡死
                        p.teleport(pos.add(0, -i + 1, 0));
                        PlayerIronElevatorEvent event = new PlayerIronElevatorEvent(p, false);
                        WIronElevator.ins.getServer().getPluginManager().callEvent(event);
                    }
                    return;
                }
            }

        }

    }
}
